'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Progress } from '@/components/ui/progress'
import { 
  Plus, 
  Search, 
  Filter, 
  MoreHorizontal,
  Edit,
  Trash2,
  Cpu,
  FileText,
  Package,
  TestTube,
  Users,
  Calendar,
  DollarSign
} from 'lucide-react'

interface HardwareVersion {
  id: string
  version: string
  name: string
  description?: string
  status: string
  schematics?: string
  pcbFiles?: string
  cost?: number
  createdAt: string
  project: {
    id: string
    name: string
    key: string
  }
  bom?: {
    id: string
    name: string
    version: string
  }
  creator: {
    id: string
    name: string
    username: string
  }
  _count: {
    tests: number
    requirements: number
  }
}

export function HardwareVersionsList() {
  const [hardwareVersions, setHardwareVersions] = useState<HardwareVersion[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [newHardwareVersion, setNewHardwareVersion] = useState({
    version: '',
    name: '',
    description: '',
    status: 'DESIGN'
  })

  useEffect(() => {
    fetchHardwareVersions()
  }, [])

  const fetchHardwareVersions = async () => {
    try {
      const response = await fetch('/api/hardware-versions')
      if (response.ok) {
        const data = await response.json()
        setHardwareVersions(data)
      }
    } catch (error) {
      console.error('Error fetching hardware versions:', error)
    } finally {
      setLoading(false)
    }
  }

  const createHardwareVersion = async () => {
    try {
      // Get the first project and user from the database
      const projectsResponse = await fetch('/api/projects')
      const projectsData = await projectsResponse.json()
      
      const usersResponse = await fetch('/api/users')
      const usersData = await usersResponse.json()
      
      if (projectsData.length === 0) {
        alert('请先创建项目')
        return
      }
      
      if (usersData.length === 0) {
        alert('请先创建用户')
        return
      }
      
      // Use the first project and user as defaults
      const projectId = projectsData[0].id
      const creatorId = usersData[0].id
      
      const response = await fetch('/api/hardware-versions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...newHardwareVersion,
          projectId,
          creatorId
        })
      })

      if (response.ok) {
        setIsCreateDialogOpen(false)
        setNewHardwareVersion({
          version: '',
          name: '',
          description: '',
          status: 'DESIGN'
        })
        fetchHardwareVersions()
      } else {
        const errorData = await response.json()
        console.error('Error creating hardware version:', errorData.error)
        alert(`创建硬件版本失败: ${errorData.error}`)
      }
    } catch (error) {
      console.error('Error creating hardware version:', error)
      alert('创建硬件版本失败，请重试')
    }
  }

  const filteredHardwareVersions = hardwareVersions.filter(hw => {
    const matchesSearch = hw.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         hw.version.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         hw.description?.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesStatus = statusFilter === 'all' || hw.status === statusFilter
    return matchesSearch && matchesStatus
  })

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      DESIGN: 'bg-blue-100 text-blue-800',
      PROTOTYPE: 'bg-yellow-100 text-yellow-800',
      TESTING: 'bg-purple-100 text-purple-800',
      VALIDATION: 'bg-orange-100 text-orange-800',
      PRODUCTION: 'bg-green-100 text-green-800',
      OBSOLETE: 'bg-gray-100 text-gray-800'
    }
    return colors[status] || 'bg-gray-100 text-gray-800'
  }

  const getStatusProgress = (status: string) => {
    const progress: Record<string, number> = {
      DESIGN: 10,
      PROTOTYPE: 30,
      TESTING: 50,
      VALIDATION: 80,
      PRODUCTION: 100,
      OBSOLETE: 100
    }
    return progress[status] || 0
  }

  if (loading) {
    return <div className="flex items-center justify-center h-64">加载中...</div>
  }

  return (
    <div className="space-y-6">
      {/* 页面标题和操作 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">硬件版本管理</h1>
          <p className="text-gray-600">管理产品硬件版本和设计迭代</p>
        </div>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              创建硬件版本
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[525px]">
            <DialogHeader>
              <DialogTitle>创建新硬件版本</DialogTitle>
              <DialogDescription>
                创建一个新的硬件版本和设计迭代
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="version" className="text-right">
                  版本号
                </Label>
                <Input
                  id="version"
                  placeholder="V1.0"
                  value={newHardwareVersion.version}
                  onChange={(e) => setNewHardwareVersion(prev => ({ ...prev, version: e.target.value }))}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">
                  名称
                </Label>
                <Input
                  id="name"
                  value={newHardwareVersion.name}
                  onChange={(e) => setNewHardwareVersion(prev => ({ ...prev, name: e.target.value }))}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="description"
                  value={newHardwareVersion.description}
                  onChange={(e) => setNewHardwareVersion(prev => ({ ...prev, description: e.target.value }))}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="status" className="text-right">
                  状态
                </Label>
                <Select
                  value={newHardwareVersion.status}
                  onValueChange={(value) => setNewHardwareVersion(prev => ({ ...prev, status: value }))}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="DESIGN">设计阶段</SelectItem>
                    <SelectItem value="PROTOTYPE">原型制作</SelectItem>
                    <SelectItem value="TESTING">测试阶段</SelectItem>
                    <SelectItem value="VALIDATION">验证阶段</SelectItem>
                    <SelectItem value="PRODUCTION">生产阶段</SelectItem>
                    <SelectItem value="OBSOLETE">已淘汰</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <DialogFooter>
              <Button onClick={createHardwareVersion}>创建版本</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* 搜索和筛选 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center space-x-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                <Input
                  placeholder="搜索硬件版本..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32">
                <Filter className="h-4 w-4 mr-2" />
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="DESIGN">设计阶段</SelectItem>
                <SelectItem value="PROTOTYPE">原型制作</SelectItem>
                <SelectItem value="TESTING">测试阶段</SelectItem>
                <SelectItem value="VALIDATION">验证阶段</SelectItem>
                <SelectItem value="PRODUCTION">生产阶段</SelectItem>
                <SelectItem value="OBSOLETE">已淘汰</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* 硬件版本列表 */}
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {filteredHardwareVersions.map((hardwareVersion) => (
          <Card key={hardwareVersion.id} className="hover:shadow-lg transition-shadow">
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="space-y-2">
                  <div className="flex items-center space-x-2">
                    <Badge className={getStatusColor(hardwareVersion.status)}>
                      {hardwareVersion.status}
                    </Badge>
                    <Badge variant="outline" className="text-xs">
                      {hardwareVersion.version}
                    </Badge>
                  </div>
                  <CardTitle className="text-lg">{hardwareVersion.name}</CardTitle>
                  <CardDescription className="line-clamp-2">
                    {hardwareVersion.description || '暂无描述'}
                  </CardDescription>
                </div>
                <Button variant="ghost" size="icon">
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </div>
              
              {/* 进度条 */}
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span>开发进度</span>
                  <span>{getStatusProgress(hardwareVersion.status)}%</span>
                </div>
                <Progress value={getStatusProgress(hardwareVersion.status)} className="h-2" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {/* 项目信息 */}
                <div className="flex items-center space-x-2 text-sm text-gray-500">
                  <Cpu className="h-4 w-4" />
                  <span>{hardwareVersion.project.key} - {hardwareVersion.project.name}</span>
                </div>

                {/* 统计信息 */}
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div className="flex items-center space-x-2">
                    <FileText className="h-4 w-4 text-blue-600" />
                    <div>
                      <div className="font-medium">{hardwareVersion._count.requirements}</div>
                      <div className="text-gray-500">需求</div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <TestTube className="h-4 w-4 text-purple-600" />
                    <div>
                      <div className="font-medium">{hardwareVersion._count.tests}</div>
                      <div className="text-gray-500">测试</div>
                    </div>
                  </div>
                </div>

                {/* 成本信息 */}
                {hardwareVersion.cost && (
                  <div className="flex items-center space-x-2 text-sm">
                    <DollarSign className="h-4 w-4 text-green-600" />
                    <span>成本: ¥{hardwareVersion.cost.toLocaleString()}</span>
                  </div>
                )}

                {/* BOM信息 */}
                {hardwareVersion.bom && (
                  <div className="flex items-center space-x-2 text-sm">
                    <Package className="h-4 w-4 text-orange-600" />
                    <span>BOM: {hardwareVersion.bom.name} v{hardwareVersion.bom.version}</span>
                  </div>
                )}

                {/* 创建信息 */}
                <div className="flex items-center justify-between text-xs text-gray-500">
                  <div className="flex items-center space-x-1">
                    <Users className="h-3 w-3" />
                    <span>{hardwareVersion.creator.name}</span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <Calendar className="h-3 w-3" />
                    <span>{new Date(hardwareVersion.createdAt).toLocaleDateString()}</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredHardwareVersions.length === 0 && (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无硬件版本</h3>
              <p className="text-gray-500 mb-4">创建您的第一个硬件版本来开始管理产品设计</p>
              <Button onClick={() => setIsCreateDialogOpen(true)}>
                <Plus className="h-4 w-4 mr-2" />
                创建硬件版本
              </Button>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}